package org.stars.dao.loader;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.stars.dao.sqlmapper.SqlMapper;
import org.stars.util.FileResourceEventHandler;
import org.stars.util.jar.FoundJarResourceEventHandler;

import static org.stars.config.Message.SOURCE_FINDER_01;
import static org.stars.config.Message.SOURCE_FINDER_02;
import static org.stars.config.Message.SOURCE_FINDER_03;
import static org.stars.config.Message.SOURCE_FINDER_04;

public class SourceFinder implements FoundJarResourceEventHandler, FileResourceEventHandler {
	protected static Log log = LogFactory.getLog(SourceFinder.class);
	protected String jarName;

	public SourceFinder() {
		loader = new XmlSqlMapperLoader();
		sqlMappers = new ArrayList<SqlMapper>();
	}

	public void clear() {
		sqlMappers = new ArrayList<SqlMapper>();
	}

	protected XmlSqlMapperLoader loader;
	protected List<SqlMapper> sqlMappers;

	public List<SqlMapper> getSqlMappers() {
		return sqlMappers;
	}

	@Override
	public void onFoundResourceEvent(String path, String resourceName, InputStream inputStream) throws Exception {
		try {
			if (jarName != null && jarName.length() > 0) {
				log.debug(SOURCE_FINDER_01.with(resourceName,path,jarName));
			} else {
				log.debug(SOURCE_FINDER_02.with(resourceName,path));
			}
			SqlMapper mapper=loader.load(resourceName, inputStream);
			mapper.setSource(resourceName+" ("+path+")");			
			sqlMappers.add(mapper);
		} catch (Exception e) {
			if (jarName != null && jarName.length() > 0) {
				log.error(SOURCE_FINDER_03.with(resourceName,path,jarName,e.getMessage()));
			} else {
				log.error(SOURCE_FINDER_04.with(resourceName,path,e.getMessage()));
			}

			throw (e);
		}
	}

	@Override
	public void setJarName(String jarName) {
		this.jarName = jarName;
	}

}

